"""
全局异常处理模块
"""
import traceback
from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError
from sqlalchemy.exc import SQLAlchemyError

from core.log import logger
from utils.response import R


async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """
    处理请求参数验证错误
    """
    logger.error(f"请求参数验证错误: {exc}")
    errors = exc.errors()
    error_messages = []
    
    for error in errors:
        field = ".".join(str(loc) for loc in error.get("loc", []))
        message = error.get("msg", "")
        error_messages.append(f"{field}: {message}")
    
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=R.err(
            msg="请求参数错误", 
            data={"errors": error_messages}, 
            code=status.HTTP_422_UNPROCESSABLE_ENTITY
        )
    )


async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
    """
    处理数据库操作错误
    """
    error_detail = str(exc)
    logger.error(f"数据库操作错误: {error_detail}")
    logger.error(traceback.format_exc())
    
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=R.err(
            msg="数据库操作错误", 
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
    )


async def pydantic_validation_handler(request: Request, exc: ValidationError):
    """
    处理Pydantic模型验证错误
    """
    logger.error(f"数据验证错误: {exc}")
    errors = exc.errors()
    error_messages = []
    
    for error in errors:
        field = ".".join(str(loc) for loc in error.get("loc", []))
        message = error.get("msg", "")
        error_messages.append(f"{field}: {message}")
    
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=R.err(
            msg="数据验证错误", 
            data={"errors": error_messages}, 
            code=status.HTTP_400_BAD_REQUEST
        )
    )


async def generic_exception_handler(request: Request, exc: Exception):
    """
    处理通用异常
    """
    error_detail = str(exc)
    logger.error(f"未处理的异常: {error_detail}")
    logger.error(traceback.format_exc())
    
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=R.err(
            msg="服务器内部错误", 
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
    ) 